import { customElement, first, OnEvent, onEvent, pull } from 'dom-native';
import { login } from '../ts/user-ctx';
import { BaseViewElement } from '../ts/v-base';

@customElement('v-login')
export class LoginView extends BaseViewElement {
	private get fieldset(): HTMLElement { return first(this, 'section.content')! }

	//#region    ---------- Element Events ---------- 
	//> In this section put all of the @onEvent bindings, which is event bound to the `this` element.

	@onEvent('click', '.btn-login')
	LoginClicked(evt: MouseEvent & OnEvent) {
		evt.preventDefault();
		this.doLogin();
	}


	//#endregion ---------- /Element Events ----------

	//#region    ---------- Lifecycle ---------- 

	init() {
		super.init();
		this.innerHTML = _render();
	}
	//#endregion ---------- /Lifecycle ---------- 
	private async doLogin() {
		const data = pull(this.fieldset);
		try {
			const result = await login(data.username, data.pwd);
			if (result.success) {
				window.location.href = '/';
				return;
			} else {
				// this.message = "登录失败，用户名或密码错误";
			}
		} catch (ex: any) {
			// this.message = "登录失败，用户名或密码错误";
		}

	}
}

function _render() {
	return `
		<div class="dialog">
			<header>RUST STARTER</header>
			<section class="content">
				<form class="form" name="loginForm" novalidate>
					<c-input name="username" placeholder="请输入用户名"></c-input>
					<c-password name="pwd" password placeholder="请输入密码"></c-password>
					<a class="action-forgot action">忘记密码</a>
					<input class="btn btn-login prim" type="submit" value="登  录"/>
				</form>
			</section>
			<footer></footer>		
		</div>
	`;
}
